package com.scs.application.modules.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.modules.base.entity.Dept;
import com.scs.application.modules.base.entity.Oprt;
import com.scs.application.modules.base.entity.Patient;
import com.scs.application.modules.base.mapper.OprtMapper;
import com.scs.application.modules.base.service.DeptService;
import com.scs.application.modules.base.service.OprtService;
import com.scs.application.modules.base.service.PatientService;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.thirdparty.dto.HisOprt;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Slf4j
@Service
public class OprtServiceImpl extends BaseServiceImpl<OprtMapper, Oprt> implements OprtService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DeptService deptService;

    @Autowired
    private PatientService patientService;


//    public List<Oprt> getOprt(String url){
//        hisService.HisMock(url);
//        return null;
//    }

    @Override
    public boolean saveOrUpdate(Oprt entity) {


        int count = this.count(Wrappers.<Oprt>query().eq("code", entity.getCode()).ne("id",entity.getId()));

        if (count > 0) {
            throw new BusinessException("手术单号不允许重复");
        }
        boolean success = super.saveOrUpdate(entity);

        return success;
    }

    public List<Oprt> oprtList(){
        List<Oprt> oprts = list(Wrappers.<Oprt>query());
        return oprts;
    }

    public RestResult syncupdata(List<HisOprt> data){
        List<Oprt> oprtSaves = new ArrayList<>();
        try {

            for (HisOprt oprts : data) {
                List<Oprt> oprtList = this.list(new QueryWrapper<Oprt>().eq("code", oprts.getCode()));
                if (!oprtList.isEmpty()) {
                    continue;
                }
                Dept dept = deptService.getOne(new QueryWrapper<Dept>().eq("his_code", oprts.getDept_code()));
                Dept deptOp = deptService.getOne(new QueryWrapper<Dept>().eq("his_code", oprts.getDept_code_op()));
                Dept deptRoom = deptService.getOne(new QueryWrapper<Dept>().eq("his_code", oprts.getDept_code_room()));

                if (dept == null) {
                    dept = new Dept();
                }
                if (deptOp == null) {
                    deptOp = new Dept();
                }
                if (deptRoom == null) {
                    deptRoom = new Dept();
                }

                Oprt oprt = new Oprt();
                oprt.setDeptId(dept.getId() != null ? dept.getId() : "0")
                        .setDeptName(dept.getName() != null ? dept.getName() : "")
                        .setDeptIdOp(deptOp.getId() != null ? deptOp.getId() : "0")
                        .setDeptOp(deptOp.getName() != null ? deptOp.getName() : "")
                        .setDeptIdRoom(deptRoom.getId() != null ? deptRoom.getId() : "0")
                        .setDeptRoom(deptRoom.getName() != null ? deptRoom.getName() : "")
                        .setCode(oprts.getCode())
                        .setDate(DateUtils.parse(oprts.getOprt_date(),"yyyy-MM-dd HH:mm:ss"))
                        .setName(oprts.getOprt_name())
                        .setSummary(oprts.getSummary())
                        .setStaffCodeApply(oprts.getStaff_code_apply())
                        .setStaffCodeSug(oprts.getStaff_code_sug())
                        .setDoctorNameSug(oprts.getDoctor_name_sug())
                        .setDoctorNameApply(oprts.getDoctor_name_apply())
                        .setPatientNo(oprts.getPatient_code())
                        .setPatientId("0")
                        .setPatientName("无")
                        .setRemark("")
                        .setStatusApply(0)
                        .setStatusCheck(0)
                        .setStatusPrep(0)
                        .setApplyDate(DateUtils.parse(oprts.getCreate_date(),"yyyy-MM-dd HH:mm:ss"))
                ;
                oprtSaves.add(oprt);
            }
            this.saveBatch(oprtSaves);
        }catch (Exception e){
            logger.error("oprt------"+e.getMessage());
            throw new BusinessException("同步失败", e);
        }

        return RestResult.ok("同步成功");
    }

    @Override
    public void syncOprtPatient() {

        List<Oprt> oprts = this.list(Wrappers.<Oprt>query().eq("patient_id", 0));
        for (Oprt oprt : oprts) {
            Patient patient = patientService.getOne(Wrappers.<Patient>query().eq("no", oprt.getPatientNo()));
            if (patient != null) {
                oprt.setPatientName(patient.getName());
                oprt.setPatientId(patient.getId());
                this.updateCascadeById(oprt);
            }
        }
    }

    @Override
    public com.scs.application.modules.base.dto.OprtDTO getOprtByCode(String code) {
        return this.baseMapper.getOprtByCode(code);
    }

    @Override
    public com.scs.application.modules.base.dto.OprtDTO getOprtById(Serializable id) {
        return this.baseMapper.getOprtById(id);
    }

    @Override
    public IPage pageForSelect(QueryContext context, Map<String, Object> userParam) {
        return this.baseMapper.pageForSelect(context.getPage(), context.getWrapper(), context.getParams(),userParam);

    }

    @Override
    public RestResult syncHisOprt(HisOprt hisOprt){
        try {
            Dept dept = deptService.getOne(new QueryWrapper<Dept>().eq("his_code", hisOprt.getDept_code()));
            Dept deptOp = deptService.getOne(new QueryWrapper<Dept>().eq("his_code", hisOprt.getDept_code_op()));
            Dept deptRoom = deptService.getOne(new QueryWrapper<Dept>().eq("his_code", hisOprt.getDept_code_room()));

            if (dept == null) {
                dept = new Dept();
            }
            if (deptOp == null) {
                deptOp = new Dept();
            }
            if (deptRoom == null) {
                deptRoom = new Dept();
            }

            Oprt oprt = new Oprt();
            oprt.setDeptId(dept.getId() != null ? dept.getId() : "0")
                    .setDeptName(dept.getName() != null ? dept.getName() : "")
                    .setDeptIdOp(deptOp.getId() != null ? deptOp.getId() : "0")
                    .setDeptOp(deptOp.getName() != null ? deptOp.getName() : "")
                    .setDeptIdRoom(deptRoom.getId() != null ? deptRoom.getId() : "0")
                    .setDeptRoom(deptRoom.getName() != null ? deptRoom.getName() : "")
                    .setCode(hisOprt.getCode())//手术单号
                    .setDate(DateUtils.parse(formatDateString(hisOprt.getOprt_date()),"yyyyMMddHHmmss"))
                    .setName(hisOprt.getOprt_name())
                    .setSummary(hisOprt.getSummary())
                    .setStaffCodeApply(hisOprt.getStaff_code_apply())
                    .setStaffCodeSug(hisOprt.getStaff_code_sug())
                    .setDoctorNameSug(hisOprt.getDoctor_name_sug())
                    .setDoctorNameApply(hisOprt.getDoctor_name_apply())
                    .setPatientNo(hisOprt.getPatient_code())
                    .setPatientId("0")
                    .setPatientName("无")
                    .setRemark("")
                    .setStatusApply(0)
                    .setStatusCheck(0)
                    .setStatusPrep(0)
                    .setApplyDate(DateUtils.parse(formatDateString(hisOprt.getCreate_date()),"yyyyMMddHHmmss"))
            ;
            Oprt old = this.getOne(new QueryWrapper<Oprt>().eq("code", hisOprt.getCode()));//通过手术单号到dept_oprt手术信息表查询一下看看原来有没有该手术申请单
            if (null != old) {
                oprt.setId(old.getId());
            }
            this.saveOrUpdate(oprt);
        }catch (Exception e){
            logger.error("his手术申请信息 同步异常，oprt------",e);
            throw new BusinessException("his手术申请信息 同步失败", e);
        }

        return RestResult.ok("his手术申请信息同步成功");
    }

    private String formatDateString(String dateStr) {
        int strLen = dateStr.length();
        if (strLen < 14) {
            while (strLen < 14) {
                StringBuffer sb = new StringBuffer();
                //sb.append("0").append(dateStr);// 左补0
                sb.append(dateStr).append("0");//右补0
                dateStr = sb.toString();
                strLen = dateStr.length();
            }
        }

        return dateStr;
    }
}
